package com.qbw.app;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.lib.util.SPUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.exception.HttpException;
import com.lzy.okgo.request.base.Request;
import com.qbw.app.manager.UserManager;
import com.qbw.app.model.User;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Response;
import okhttp3.ResponseBody;

public abstract class JsonCallback<T> extends AbsCallback<T> {
    private Type type;
    private Class<T> clazz;

    public JsonCallback() {
    }

    public JsonCallback(Type type) {
        this.type = type;
    }

    public JsonCallback(Class<T> clazz) {
        this.clazz = clazz;
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
//        if (NetworkUtils.isWifiConnected()|| NetworkUtils.isMobileData()) {
//            if (!TextUtils.isEmpty(SPUtils.getInstance().getString("USER_TOKEN", ""))) {
//                if(request.getBaseUrl().startsWith("https://www.renrenfo.com")){
//                    request.headers("Cache-Control", "no-cache")
//                            .headers("x-client-model","android")
//                            .headers("x-client-version",  AppUtils.getAppVersionName()+"")
//                            .headers("x-client-code",AppUtils.getAppVersionCode()+"")
//                            .headers("x-client-bundleid",AppUtils.getAppInfo().getPackageName()+"")
//                            .headers("x-client-deviceuuid",  Constants.UUID +"")
//                            .headers("Authorization", "Bearer " + SPUtils.getInstance().getString("USER_FXT_TOKEN"));
//                }else{
//                    request.headers("Cache-Control", "no-cache")
//                            .headers("x-client-model","android")
//                            .headers("x-client-version",  AppUtils.getAppVersionName()+"")
//                            .headers("x-client-code",AppUtils.getAppVersionCode()+"")
//                            .headers("x-client-bundleid",AppUtils.getAppInfo().getPackageName()+"")
//                            .headers("x-client-deviceuuid",  Constants.UUID +"")
//                            .headers("Authorization", "Bearer " + SPUtils.getInstance().getString("USER_TOKEN"));
//                }
//            }else{
//                request.headers("Cache-Control", "no-cache")
//                        .headers("x-client-model","android")
//                        .headers("x-client-version",  AppUtils.getAppVersionName()+"")
//                        .headers("x-client-code",AppUtils.getAppVersionCode()+"")
//                        .headers("x-client-bundleid",AppUtils.getAppInfo().getPackageName()+"")
//                        .headers("x-client-deviceuuid",  Constants.UUID +"");
//            }
//        }else{
////            ARouter.getInstance()
////                    .build(Constants.ACTIVITY_URL_BASE_CONFIG)
////                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK )
////                    .withInt(Constants.TYPE, Constants.NOT_NETWORK)
////                    .navigation();
//        }
        User user = UserManager.getInstance().getUser();
        String token = user != null ? user.getToken() : null;

        request.headers("Cache-Control", "no-cache")
                        .headers("x-client-model","android")
                .headers("Authorization", token);
    }

    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        Throwable exception = response.getException();
        if (exception instanceof UnknownHostException || exception instanceof ConnectException) {
        } else if (exception instanceof SocketTimeoutException) {
        } else if (exception instanceof HttpException) {
        }else{
            if(response.getRawResponse()!=null){
                String result = null;
                try {
                    result = response.getRawResponse().body().string();

                }catch (Exception e){

                }

            }
        }
    }


    /**
     * 该方法是子线程处理，不能做ui相关的工作
     * 主要作用是解析网络返回的 response 对象,生产onSuccess回调中需要的数据对象
     * 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
     */
    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        T data = null;

        JsonReader jsonReader = new JsonReader(body.charStream());
        Gson gson = new GsonBuilder()
                .create();
        if (response.code() < 300 && response.code() >= 200) {
            if (type != null) {
                data = gson.fromJson(jsonReader, type);
            } else if (clazz != null) {
                data = gson.fromJson(jsonReader, clazz);
            } else {
                Type genType = getClass().getGenericSuperclass();
                Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
                data = gson.fromJson(jsonReader, type);
            }
        } else {
            throw new IllegalStateException();
        }

        return data;
    }

}
